package com.google.appengine.echogear.jobs;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.google.appengine.echogear.core.EchoJob;

public final class TencentWeiboJob extends EchoJob {

	private static final long serialVersionUID = 2763790516718179900L;

	public TencentWeiboJob() {
		super();
	}

	@Override
	public boolean init() {
		return true;
	}

	@Override
	public boolean send(String messgae) {
		try {
			URL url = new URL("http://open.t.qq.com/api/t/add");
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod("POST");
	        connection.setDoOutput(true);
	        
	        String[] param = this.getParam().split(",");
	        StringBuffer params = new StringBuffer();
	        params.append("access_token").append("=").append(param[0]).append("&")
	              .append("content").append("=").append(URLEncoder.encode(messgae, "utf-8")).append("&")
	              .append("format").append("=").append("json").append("&")
	              .append("clientip").append("=").append("210.83.161.184").append("&")
	              .append("openid").append("=").append("9B69BFF8267BD9F37FBF06821BA793C9").append("&")
	              .append("oauth_consumer_key").append("=").append("801143519").append("&")
	              .append("oauth_version").append("=").append("2.a").append("&")
	              .append("scope").append("=").append("all");
	        byte[] bypes = params.toString().getBytes();
	        connection.getOutputStream().write(bypes);
	        InputStream inStream=connection.getInputStream();
	        System.out.println(new String(readInputStream(inStream), "utf-8"));
        } catch (Exception e) {
        	return false;
        }
		return true;		
	}
	
	public byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}
